package com.lap.auth.application.user;

import com.lap.auth.domain.user.event.UserAssignedEvent;
import com.lap.auth.domain.user.repository.UserRoleRepository;
import com.lap.auth.domain.user.service.UserRoleValidator;
import com.lap.auth.domain.user.service.UserValidator;
import java.util.List;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
public class UserRoleAppService {

  private final UserValidator userValidator;
  private final UserRoleValidator userRoleValidator;
  private final UserRoleRepository userRoleRepository;
  private final ApplicationEventPublisher publisher;

  @Transactional(rollbackFor = Exception.class)
  public void assignRoles(Integer userId, Set<Integer> roleSet) {
    userValidator.assertUserExists(userId);
    userRoleValidator.validateRolesExist(roleSet);

    userRoleRepository.deleteByUserId(userId);
    if (CollectionUtils.isNotEmpty(roleSet)) {
      userRoleRepository.saveAll(userId, roleSet);
    }

    publisher.publishEvent(new UserAssignedEvent(userId, roleSet));
  }

  public List<Integer> queryRolesByUserId(Integer userId) {
    userValidator.assertUserExists(userId);
    return userRoleRepository.findByUserId(userId);
  }
}
